import JSONAPISerializer from "json-api-serializer"
import request from "../../utils/request";
import flarum from "../../flarum";
import {urlEncode} from "../../utils/tools";

export class Detail {
    constructor() {
        const that = this
        that.serializer = new JSONAPISerializer()

        that.serializer.register("discussions", {
            id: "id",
            relationships: {
                posts: {
                    type: "posts"
                },
                users: {
                    type: "users"
                },
                groups: {
                    type: "groups"
                },
                tags: {
                    type: "tags"
                },
                discussionviews: {
                    type: "discussionviews"
                },
                discussions: {
                    type: "discussions"
                },
            },
            topLevelMeta: function(data, extraData) {
                return {
                    count: extraData.count,
                    total: data.length
                };
            }
        })

        that.serializer.register('tags', {
            type: "tags",
            id: "id"
        })

        that.serializer.register('posts', {
            type: "posts",
            id: "id"
        })

        that.serializer.register('users', {
            type: "users",
            id: "id"
        })

        that.serializer.register('groups', {
            type: "groups",
            id: "id"
        })

        that.serializer.register('discussionviews', {
            type: "discussionviews",
            id: "id"
        })

        that.serializer.register('discussions', {
            type: "discussions",
            id: "id"
        })
    }

    /**
     * 获取API地址
     * @param id
     * @param near
     * @returns {string}
     */
    getApi(id, near = 0) {
        return `${flarum.api}/discussions/${id}?bySlug=true&page[near]=${near}`
    }

    /**
     * 执行详细结果
     * @param id
     * @param func
     */
    execute(id, func) {
        const that = this
        const url = that.getApi(id)
        request.get(url).then(res => {
            that.data = res
            that.viewdata = that.serializer.deserialize("discussions", res)
            func(that.data, that.viewdata)
        }).catch(res => {})
    }
}